package cn.jsu.oj.dispatchServer.satellite.heart;

import cn.jsu.oj.dispatchServer.satellite.netty.starter.SatelliteStarter;
import cn.jsu.oj.dispatchServer.satellite.pojo.net.HeartBeatNet;
import cn.jsu.oj.dispatchServer.satellite.server.SatelliteServer;
import cn.jsu.oj.dispatchServer.satellite.util.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;

import java.util.Arrays;

/**
 * 心跳逻辑
 *
 * @author shan
 * @date 2022/06/29
 */
@Slf4j
public class HeartClientHeartJob implements Job {

    Scheduler scheduler;

    SatelliteServer satelliteServer;

    HeartClientService heartClientService;

    public HeartClientHeartJob() {
        scheduler = (Scheduler) SpringUtil.getBean("scheduler");
        satelliteServer = (SatelliteServer) SpringUtil.getBean("satelliteServer");
        heartClientService = (HeartClientService) SpringUtil.getBean("heartClientService");
    }

    @Override
    public void execute(JobExecutionContext jobExecutionContext) {
        if (SatelliteStarter.activeSign && SatelliteStarter.verifySign) {
            try {
//                log.info("----------心跳触发......");
                satelliteServer.getChannel().writeAndFlush(new HeartBeatNet().serialize());
            } catch (Exception e) {
                e.printStackTrace();
                log.error("----------心跳发送失败......");
                log.error(Arrays.toString(e.getStackTrace()));
            }
        } else {
            if (satelliteServer.getChannel() != null) {
                satelliteServer.close();
            }
            log.error("----------连接中断，心跳调度移除......");
            heartClientService.brokenHeart();
        }
    }
}
